package com.alibaba.csp.sentinel.dashboard.rule.nacos.degrade;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * <h1>
 * 用于从 Nacos 拉取熔断规则配置
 * </h1>
 */
@Component("degradeRuleNacosProvider")
public class DegradeRuleNacosProvider implements DynamicRuleProvider<List<DegradeRuleEntity>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DegradeRuleNacosProvider.class);

    private final ConfigService configService;

    private final Converter<String, List<DegradeRuleEntity>> converter;

    public DegradeRuleNacosProvider(ConfigService configService, Converter<String, List<DegradeRuleEntity>> converter) {
        this.configService = configService;
        this.converter = converter;
    }


    @Override
    public List<DegradeRuleEntity> getRules(String appName) throws Exception {
        String rules = configService
                .getConfig(appName + NacosConfigUtil.DEGRADE_DATA_ID_POSTFIX,
                        NacosConfigUtil.GROUP_ID, 3000);
        LOGGER.info("get degrade rule from nacos ,rules: {}", rules);
        if (StringUtil.isBlank(rules)) {
            return new ArrayList<>();
        }
        return converter.convert(rules);
    }
}
